import type { ActionType } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Form, Select, message, Modal, Spin, Button } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';
import { handledynamicquerydata, handledynamicqueryColumns } from '@/utils'
import { request } from 'umi';
import MyEcharts from '@/components/myEcharts'
import EditCom from './edit';
import './apilist.less'
import { PlusOutlined } from '@ant-design/icons';
export const waitTimePromise = async (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

export const waitTime = async (time: number = 100) => {
  await waitTimePromise(time);
};

export default (props: any) => {
  const requestsUrls = {
    optionUrl: '/data/dynamic/query',
    list: "/data/dynamic/query",
  };
  const [loading, setloading] = useState(false);
  const [wherecolumns, setwherecolumns]: any = useState([]);
  const deleteFn = (id) => {
    Modal.confirm({
      title: '确认删除？',
      content: '',
      onOk() {

        request(requestsUrls.delete, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          data: {
            apiID: 'DMT_MNG_02_03',
            apiParam: {
              api_id: id
            }
          },
        }).then((res) => {
          message.success(res?.meta?.msg);
          actionRef.current?.reload();
        })
      },
      onCancel() {
        console.log('Cancel')
      }
    })
  }
  const scancolumns = [
    {
      title: '接口名称',
      key: 'api_name',
      dataIndex: 'api_name',
      hideInTable: true,
    },
    {
      title: '接口ID',
      key: 'api_id',
      dataIndex: 'api_id',
      hideInTable: true,
    }, {
      title: '操作',
      key: 'scan',
      fixed: 'right',
      dataIndex: 'scan',
      hideInSearch: true,
      width: 140,
      render: (text, record, index) => {
        return <>
          <Button type="link" onClick={() => {
            props.onOk(record);
          }}>选择</Button>
        </>
      }
    }]
  const [columns, setcolumns]: any = useState([]);
  const [datasource, setdatasource]: any = useState([]);
  const [paging, setpaging] = useState({});
  const [orderBy, setorderBy] = useState('api_id');
  const [where, setwhere]: any = useState([]);
  const actionRef = useRef<ActionType>();
  const editRef = useRef();
  const access = useAccess();
  const [form] = Form.useForm(); //搜索表单
  // const pageAuth = access[props.route.key] || {edit:true,delete:true,add:true};
  return (
    <>

      {
        loading ? <Spin>配置加载中</Spin> : <ProTable
          actionRef={actionRef}
          scroll={{ x: 'max-content', y: window.innerHeight - 480 }}
          columns={wherecolumns.concat(columns).concat(scancolumns)}
          // search={false}
          params={form.getFieldsValue()}
          // params 是需要自带的参数
          // 这个参数优先级更高，会覆盖查询表单的参数
          request={async (
            // 第一个参数 params 查询表单和 params 参数的结合
            // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
            params: T & {
              pageSize: number;
              //current: number;
            },
            sort,
            filter,
          ) => {
            // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
            // 如果需要转化参数可以在这里进行修改
            const paramsdata: any = {
              "apiID": "DMT_MNG_02",
              "apiParam": {
                'orderBy': orderBy,
                "paging": { "pageSize": params.pageSize, "pageNum": params.current },
                "where": []
              }
            };
            if (params.api_name) {
              paramsdata['apiParam']['where'].push({
                connector: "like",
                'feild': "api_name",
                'value': params.api_name
              });
            }
            if (params.api_id) {
              paramsdata['apiParam']['where'].push({
                connector: "like",
                'feild': "api_id",
                'value': params.api_id
              });
            }
            where.map((e: any, i: Number) => {
              console.log(e);
              if (params[e.key]) {
                paramsdata?.apiParam.where.push({
                  "feild": e.key,
                  "connector": e.connector,
                  "value": params[e.key]
                })
              }
            })
            //where
            const response: any = await request(requestsUrls.list, {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
              },
              data: paramsdata,
            });
            const rescolumns = response?.data?.columns || [];

            const columnsn = handledynamicqueryColumns(rescolumns);
            setcolumns(columnsn);
            setdatasource(response?.data?.data || [])
            return {
              data: response?.data?.data || [],
              // success 请返回 true，
              // 不然 table 会停止解析数据，即使有数据
              success: true,
              // 不传会使用 data 的长度，如果是分页一定要传
              total: response?.data?.count,
              //message.success(res?.meta?.msg);
            };
          }}
        />
      }

      <div></div>

      <EditCom
        ref={editRef}
        callback={() => {
          actionRef.current?.reload();
        }}
      />
    </>
  );
};
